package com.chungkui.bond.authmanager.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chungkui.bond.authmanager.bean.Permission;
import com.chungkui.bond.authmanager.bean.RoleInfo;
import com.chungkui.bond.authmanager.bean.RolePermission;
import com.chungkui.bond.authmanager.bean.RoleRouter;
import com.chungkui.bond.authmanager.client.ReloadPermissionClient;
import com.chungkui.bond.authmanager.service.PermissionService;
import com.chungkui.bond.authmanager.service.RoleInfoService;
import com.chungkui.bond.common.core.api.ResBus;
import com.chungkui.bond.microservice.resource.util.SecurityUtils;
import com.google.common.collect.Sets;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;

/**
 * Copyright (C), 2019-2020, JASON
 * 角色管理
 *
 * @author JASON
 * @fileName: RoleInfoController
 * @date: 23/05/2019 10:41
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@RestController
@RequestMapping("/role")
public class RoleInfoController {
    private final static Logger LOG = LoggerFactory.getLogger(RoleInfoController.class);

    @Autowired
    RoleInfoService roleInfoService;

    @Autowired
    ReloadPermissionClient reloadPermissionClient;

    @Autowired
    PermissionService permissionService;
    @GetMapping("/list")
    public Object list(Page iPage, RoleInfo roleInfo) {
        //获取所有角色
        //0.查询条件；1.list数据；2.分页数据；
        QueryWrapper<RoleInfo> queryWrapper = new QueryWrapper<RoleInfo>();
        queryWrapper.setEntity(roleInfo);
        queryWrapper.orderByAsc("role_code");
        IPage<RoleInfo> roleInfoList = roleInfoService.page(iPage, queryWrapper);
        return ResBus.success(roleInfoList);
    }

    @GetMapping("/all")
    public Object listAll() {
        return ResBus.success(roleInfoService.list());
    }

    /**
     * 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @param roleCode
     * @return
     * @throws
     * @Author admin
     * @date 23/05/2019 11:08
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @GetMapping("/delete/{roleCode}")
    public Object delete(@PathVariable("roleCode") String roleCode, HttpServletRequest request, HttpServletResponse response) {
        roleInfoService.deleteRoleByCode(roleCode);
        return ResBus.success("删除成功");
    }

    @PostMapping("/save")
    public Object saveObject(RoleInfo roleInfo, String permissions, String routers, String clientId, HttpServletRequest request, HttpServletResponse response) {
        RoleInfo roleinfo = roleInfoService.getById(roleInfo.getRoleCode());
        String msg = "新增角色成功！";
        if (roleinfo == null) {
            roleInfo.setCreateTime(new Date());
            roleInfo.setIsValid("T");
            roleInfo.setCreator(SecurityUtils.getUsername());
        } else {
            roleInfo.setUpdateTime(new Date());
            roleInfo.setUpdator(SecurityUtils.getUsername());
            msg = "权限更新成功！";
        }
        List<RolePermission> rolePermissions = new ArrayList<RolePermission>();
        if (!StringUtils.isBlank(permissions)) {
            for (String permission : permissions.split(",")) {
                RolePermission rolePermission = new RolePermission();
                rolePermission.setPermissionId(permission);
                rolePermission.setRoleCode(roleInfo.getRoleCode());
                rolePermissions.add(rolePermission);
            }

        }

        List<RoleRouter> roleRouters = new ArrayList<RoleRouter>();
        if (!StringUtils.isBlank(routers)) {
            for (String routerId : routers.split(",")) {
                RoleRouter roleRouter = new RoleRouter();
                roleRouter.setClientId(clientId);
                roleRouter.setRoleCode(roleInfo.getRoleCode());
                roleRouter.setRouterId(routerId);
                roleRouters.add(roleRouter);
            }
        }
        roleInfoService.saveRoleSetting(roleInfo, rolePermissions, roleRouters);
        if (StringUtils.isNotEmpty(permissions)) {
            List<Permission> ps = permissionService.listByIds(Arrays.asList(permissions.split(",")));
            Set<String> sps = Sets.newHashSet();
            for (Permission permission : ps) {
                sps.add(permission.getClientId());
            }
            if (CollectionUtils.isNotEmpty(sps)) {
                for (String c : sps) {
                    try {
                        reloadPermissionClient.reload(new URI("http://"+c + "/sys/reloadPermission"),permissions);
                    } catch (URISyntaxException e) {
                        LOG.error("reloadPermissionClient reload error",e);
                    }
                }
            }
        }


        return ResBus.success(msg);
    }

    @GetMapping("/listPerAndRouter/{roleCode}")
    public Object listPerAndRouter(@PathVariable("roleCode") String roleCode, HttpServletRequest request, HttpServletResponse response) {
        List<String> routers = roleInfoService.listRoutersByRole(roleCode);
        List<String> permissions = roleInfoService.listPermissionByRole(roleCode);
        JSONObject obj = new JSONObject();
        obj.put("roleRouters", routers);
        obj.put("rolePermissions", permissions);
        return ResBus.success(obj);
    }

}
